package dtn.news;

import java.io.IOException;
import java.nio.channels.AsynchronousCloseException;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import dtn.getdata.AndroidDataFactory;
import dtn.getdata.AndroidGetData;
import dtn.getdata.ConvertTools;
import dtn.models.News;
import dtn.supports.Constant;
import dtn.supports.DatabaseHelper;
import dtn.supports.ListNewsAdapter;
import dtn.supports.PreferenceConnector;
import dtn.supports.Settings;
import dtn.supports.Tools;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract.CommonDataKinds.Event;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class PageMain extends Activity {

	private ImageView imgDetailTitle;
	private Button btnShorten;
	private Animation aniLTC;
	private Animation aniCTR;
	private Animation aniRTC;
	private Animation aniCTL;
	private Animation aniSD;
	private Animation aniSU;
	private boolean isShorten;
	private Button btnNews;
	private Button btnCareer;
	private Button btnScience;
	private Button btnIntro;
	private boolean isNewsChoose;
	private boolean isCareerChoose;
	private boolean isScienceChoose;
	private boolean isIntroChoose;
	private TextView txtTitle;
	private int widthView;
	private ListView lstNews;
	private ListView lstCareer;
	private ListView lstScience;
	private ImageView imgIntro;
	private ArrayList<News> dataNews;
	private ArrayList<News> dataCareer;
	private ArrayList<News> dataScience;
	private ListNewsAdapter adapterNews;
	private ListNewsAdapter adapterCareer;
	private ListNewsAdapter adapterScience;
	private ArrayList<News> tempData;
	private UINewNewsHandler uiNewsHandler;
	private UINewScienceHandler uiScienceHandler;
	private UINewCareerHandler uiCareerHandler;
	private UIPageDetailHandler uiPageDetailHandler;
	private int pageNewsIndex = 1;
	private int pageCareerIndex = 1;
	private int pageScienceIndex = 1;
	private DatabaseHelper database;
	private final int touchSpace = 50;
	private Button btnSeeMore;
	private Timer timer;
	private int timer_count = 0;
	private ProgressBar pgrLoading;
	private String htmlContent = "";
	private String urlDetailView = "";
	private ProgressDialog prdWaiting;
	protected int newsFirstVisibleItem = 0;
	protected int careerFirstVisibleItem = 0;
	protected int careerVisibleItemCount = 0;
	protected int scienceFirstVisibleItem = 0;
	protected int scienceVisibleItemCount = 0;
	private TextView txtUpdate;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.page_main);

		// Animation
		InitAnimation();

		// Layout Detail Title
		InitLayoutTitle();

		// Init Layout Content
		InitContent();

		// Init Menu
		InitMenu();

		// Init Data
		InitData();

		// Init UI Handler
		InitUIHandler();

		// Init Settings
		InitSettings();

		// Init Timer
		InitTimer();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.page_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Cap nhat thong tin
		if (item.getItemId() == R.id.update) {
			// Thuc hien cap nhat
			pgrLoading.setVisibility(View.VISIBLE);
			updateDataFromInternet();
			return (true);
		}

		// Tuy chinh cau hinh
		else if (item.getItemId() == R.id.settings) {
			startActivity(new Intent(this, PageSetting.class));
			InitSettings();
			return (true);
		}
		return super.onOptionsItemSelected(item);
	}

	// =================KHỐI HÀM KHỞI TẠO==================
	/**
	 * Init Timer
	 */
	private void InitTimer() {
		timer = new Timer();
		timer.scheduleAtFixedRate(new TimerTask() {

			@Override
			public void run() {
				if (timer_count >= Settings.TimeAutoUpdate
						&& Settings.IsAutoUpdate) {
					updateDataFromInternet();
				}
			}
		}, 0, 60 * 1000);
	}

	/**
	 * Init settings
	 */
	private void InitSettings() {
		int defaultValue = Constant.DEFAULT_NEWS + Constant.MIN_NEWS;
		Settings.setSettings(PreferenceConnector.readBoolean(this,
				Constant.KEY_AUTO_UPDATE, false), PreferenceConnector
				.readInteger(this, Constant.KEY_TIME_UPDATE,
						Constant.MIN_TIME_AUTO_UPDATE), PreferenceConnector
				.readInteger(this, Constant.KEY_AMOUNT_NEWS, defaultValue),
				PreferenceConnector.readInteger(this,
						Constant.KEY_AMOUNT_SCIENCE, defaultValue),
				PreferenceConnector.readInteger(this,
						Constant.KEY_AMOUNT_CAREER, defaultValue));
		Settings.loadSettings();
	}

	/**
	 * Init data for list view
	 */
	private void InitData() {
		// init database
		database = new DatabaseHelper(getApplicationContext());

		// create data list
		dataCareer = new ArrayList<News>();
		dataNews = new ArrayList<News>();
		dataScience = new ArrayList<News>();

		// create temp data
		tempData = new ArrayList<News>();

		// new news data
		adapterNews = new ListNewsAdapter(dataNews, PageMain.this);
		lstNews.setAdapter(adapterNews);
		getNewsDataFromDatabase(DatabaseHelper.Table_TinMoi, dataNews,
				adapterNews);

		// new career data
		adapterCareer = new ListNewsAdapter(dataCareer, PageMain.this);
		lstCareer.setAdapter(adapterCareer);
		getNewsDataFromDatabase(DatabaseHelper.Table_ViecLam, dataCareer,
				adapterCareer);

		// new science data
		adapterScience = new ListNewsAdapter(dataScience, PageMain.this);
		lstScience.setAdapter(adapterScience);
		getNewsDataFromDatabase(DatabaseHelper.Table_KhoaHoc, dataScience,
				adapterScience);
		// updateDataFromInternet();
	}

	// Init UI Handler
	private void InitUIHandler() {
		uiNewsHandler = new UINewNewsHandler();
		uiCareerHandler = new UINewCareerHandler();
		uiScienceHandler = new UINewScienceHandler();
		uiPageDetailHandler = new UIPageDetailHandler();
	}

	// Khởi tạo giao diện ảnh tiêu đề
	private void InitLayoutTitle() {

		imgDetailTitle = (ImageView) findViewById(R.id.img_detail_title);
		imgDetailTitle.setAnimation(aniSU);
		imgDetailTitle.setAnimation(aniSD);
		btnShorten = (Button) findViewById(R.id.btn_shorten);
		btnShorten.setOnClickListener(shortenClickListener);
		txtTitle = (TextView) findViewById(R.id.txt_title);
		txtUpdate = (TextView) findViewById(R.id.txt_update);
		txtUpdate.setVisibility(View.GONE);
		pgrLoading = (ProgressBar) findViewById(R.id.pgrLoading);
		prdWaiting = new ProgressDialog(PageMain.this, R.style.Theme_MyDialog);
		prdWaiting.setTitle("Chờ giây lát...");
		prdWaiting.setCancelable(true);

	}

	// Khởi tạo các list nội dung
	private void InitContent() {

		widthView = getWindowManager().getDefaultDisplay().getWidth();

		// List News
		lstNews = (ListView) findViewById(R.id.list_news);
		lstNews.setAnimation(aniCTL);
		lstNews.setAnimation(aniRTC);
		lstNews.setAnimation(aniLTC);
		lstNews.setAnimation(aniSD);
		lstNews.setOnTouchListener(lstNewsOnTouchListener);
		lstNews.setOnItemClickListener(lstItemClickListener);
		lstNews.setOnScrollListener(lstOnScrollListener);
		isNewsChoose = true;

		// List Career
		lstCareer = (ListView) findViewById(R.id.list_career);
		lstCareer.setAnimation(aniRTC);
		lstCareer.setAnimation(aniLTC);
		lstCareer.setAnimation(aniCTR);
		lstCareer.setAnimation(aniCTL);
		lstCareer.setAnimation(aniSD);
		lstCareer.setOnScrollListener(lstOnScrollListener);
		lstCareer.setVisibility(View.GONE);
		lstCareer.setOnItemClickListener(lstItemClickListener);
		lstCareer.setOnTouchListener(lstCareerOnTouchListener);

		// List Science
		lstScience = (ListView) findViewById(R.id.list_science);
		lstScience.setAnimation(aniRTC);
		lstScience.setAnimation(aniLTC);
		lstScience.setAnimation(aniCTR);
		lstScience.setAnimation(aniSD);
		lstScience.setOnScrollListener(lstOnScrollListener);
		lstScience.setVisibility(View.GONE);
		lstScience.setOnItemClickListener(lstItemClickListener);
		lstScience.setOnTouchListener(lstScienceOnTocuhListener);

		// Image intro
		imgIntro = (ImageView) findViewById(R.id.img_intro);
		imgIntro.setAnimation(aniSD);
		imgIntro.setVisibility(View.INVISIBLE);

	}

	// Khởi tạo các nút bấm
	private void InitMenu() {
		// LayoutMenu
		btnNews = (Button) findViewById(R.id.btn_news);
		btnNews.setOnClickListener(btnNewsClickListener);

		btnCareer = (Button) findViewById(R.id.btn_career);
		btnCareer.setOnClickListener(btnCareerClickListener);

		btnScience = (Button) findViewById(R.id.btn_science);
		btnScience.setOnClickListener(btnScienceClickListener);

		btnIntro = (Button) findViewById(R.id.btn_intro);
		btnIntro.setOnClickListener(btnIntroClickListener);

		btnSeeMore = (Button) findViewById(R.id.btn_seemore);
		btnSeeMore.setOnClickListener(btnSeeMoreClickListener);
		btnSeeMore.setVisibility(View.GONE);
	}

	// Khởi tạo hiệu ứng
	private void InitAnimation() {

		// Trượt từ trái vào giữa
		aniLTC = AnimationUtils.loadAnimation(this, R.anim.left_to_center);
		aniLTC.setInterpolator((new AccelerateDecelerateInterpolator()));
		aniLTC.setFillEnabled(true);

		// Trượt từ giữa qua phải
		aniCTR = AnimationUtils.loadAnimation(this, R.anim.center_to_right);
		aniCTR.setInterpolator((new AccelerateDecelerateInterpolator()));
		aniCTR.setFillEnabled(true);

		// Trượt từ phải vào giữa
		aniRTC = AnimationUtils.loadAnimation(this, R.anim.right_to_center);
		aniRTC.setInterpolator((new AccelerateDecelerateInterpolator()));
		aniCTR.setFillEnabled(true);

		// Trượt từ giữa qua trái
		aniCTL = AnimationUtils.loadAnimation(this, R.anim.center_to_left);
		aniCTL.setInterpolator((new AccelerateDecelerateInterpolator()));
		aniCTL.setFillEnabled(true);

		// Giãn từ trên xuống
		aniSD = AnimationUtils.loadAnimation(this, R.anim.swipe_down);
		aniSD.setInterpolator((new AccelerateDecelerateInterpolator()));
		aniSD.setFillEnabled(true);

		// Thu từ dưới lên
		aniSU = AnimationUtils.loadAnimation(this, R.anim.swipe_up);
		aniSU.setInterpolator((new AccelerateDecelerateInterpolator()));
		aniSU.setFillEnabled(true);
	}

	// =================KHỐI HÀM SỰ KIỆN===================

	// Nút bấm thu gọn
	private OnClickListener shortenClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			isShorten = !isShorten;

			if (isShorten) {
				// Thực hiện animation thu gọn image
				imgDetailTitle.setVisibility(View.GONE);
				btnShorten.setBackgroundResource(R.drawable.btn_shorten_down);

			} else {
				// Thực hiện animationn giãn hình từ trên xuống
				btnShorten.setBackgroundResource(R.drawable.btn_shorten_up);
				imgDetailTitle.setVisibility(View.VISIBLE);
			}
		}
	};

	// Nút bấm tin tức
	private OnClickListener btnNewsClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (!isNewsChoose) {
				setOffAllButton();

				// Hiệu ứng btnNews
				isNewsChoose = true;
				btnNews.setBackgroundResource(R.drawable.btn_news_down);

				// Hiệu ứng của listNews
				lstNews.startAnimation(aniSD);
				setInvisibleView();
				lstNews.setVisibility(View.VISIBLE);
				LoadPages();
			}
		}
	};

	// Nút bấm việc làm
	private OnClickListener btnCareerClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (!isCareerChoose) {
				setOffAllButton();

				// Hiệu ứng btnCareer
				isCareerChoose = true;
				btnCareer.setBackgroundResource(R.drawable.btn_career_down);

				// Hiệu ứng lstCareer
				lstCareer.startAnimation(aniSD);
				setInvisibleView();
				lstCareer.setVisibility(View.VISIBLE);
				LoadPages();
			}
		}
	};

	// Nút bấm khoa học
	private OnClickListener btnScienceClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (!isScienceChoose) {
				setOffAllButton();

				// Hiệu ứng btnScience
				isScienceChoose = true;
				btnScience.setBackgroundResource(R.drawable.btn_science_down);

				// Hiệu ứng lstScience
				lstScience.startAnimation(aniSD);
				setInvisibleView();
				lstScience.setVisibility(View.VISIBLE);
				LoadPages();
			}
		}
	};

	// Nút bấm giới thiệu
	private OnClickListener btnIntroClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (!isIntroChoose) {
				setOffAllButton();

				// Hiệu ứng btnCareer
				isIntroChoose = true;
				btnIntro.setBackgroundResource(R.drawable.btn_intro_down);

				// Hiệu ứng imgIntro
				imgIntro.startAnimation(aniSD);
				setInvisibleView();
				imgIntro.setVisibility(View.VISIBLE);
			}
		}
	};

	// Nút bấm xem thêm
	private OnClickListener btnSeeMoreClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (isCareerChoose) {
				pgrLoading.setVisibility(View.VISIBLE);
				getPageCareer(pageCareerIndex);
				pageCareerIndex++;
			} else if (isScienceChoose) {
				pgrLoading.setVisibility(View.VISIBLE);
				getPageScience(pageScienceIndex);
				pageScienceIndex++;
			}

		}

	};

	// Sự kiện chạm trên listNews
	private OnTouchListener lstNewsOnTouchListener = new OnTouchListener() {

		private float upX;
		private float downX;
		private float downY;
		private float upY;

		@Override
		public boolean onTouch(View v, MotionEvent event) {

			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN: {
				downX = event.getX();
				downY = event.getY();
				break;
			}

			case MotionEvent.ACTION_MOVE: {
				upY = event.getY();
				if (downY < upY && newsFirstVisibleItem == 0
						&& pgrLoading.getVisibility() == View.GONE) {
					txtUpdate.setVisibility(View.VISIBLE);
				} else {
					txtUpdate.setVisibility(View.GONE);
				}
				break;
			}

			case MotionEvent.ACTION_UP: {
				upX = event.getX();

				if (isNewsChoose) {
					if (downX < upX && downX < touchSpace) {
						// Thực hiện trượt trừ News -> Science
						doSwipeLTR(lstNews, lstScience, btnScience,
								R.drawable.btn_science_down);
						isScienceChoose = true;
						LoadPages();
						return true;
					}

					if (downX > upX && downX > widthView - touchSpace) {
						// Thực hiện trượt từ News -> Career
						doSwipeRTL(lstNews, lstCareer, btnCareer,
								R.drawable.btn_career_down);
						isCareerChoose = true;
						LoadPages();
						return true;
					}

					// Cap nhat thong tin
					if (txtUpdate.getVisibility() == View.VISIBLE) {
						txtUpdate.setVisibility(View.GONE);
						pgrLoading.setVisibility(View.VISIBLE);
						updateDataFromInternet();
					}
				}

				break;
			}
			}
			return false;
		}

	};

	// Sự kiện chạm trên listCareer
	private OnTouchListener lstCareerOnTouchListener = new OnTouchListener() {

		private float downX;
		private float upX;
		private float upY;
		private float downY;

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN: {
				downX = event.getX();
				downY = event.getY();
				break;
			}

			case MotionEvent.ACTION_MOVE: {
				upY = event.getY();
				if (downY < upY && careerFirstVisibleItem == 0
						&& pgrLoading.getVisibility() == View.GONE) {
					txtUpdate.setVisibility(View.VISIBLE);
				} else {
					txtUpdate.setVisibility(View.GONE);
				}
				break;
			}

			case MotionEvent.ACTION_UP: {
				upX = event.getX();

				if (isCareerChoose) {
					if (downX < upX && downX < touchSpace) {
						// Thực hiện trượt từ Career -> News
						doSwipeLTR(lstCareer, lstNews, btnNews,
								R.drawable.btn_news_down);
						isNewsChoose = true;
						LoadPages();
						return true;
					}

					if (downX > upX && downX > widthView - touchSpace) {
						// Thực hiện trượt từ Career -> Science
						doSwipeRTL(lstCareer, lstScience, btnScience,
								R.drawable.btn_science_down);
						isScienceChoose = true;
						LoadPages();
						return true;
					}

					// Cap nhat thong tin
					if (txtUpdate.getVisibility() == View.VISIBLE) {
						txtUpdate.setVisibility(View.GONE);
						pgrLoading.setVisibility(View.VISIBLE);
						updateDataFromInternet();
					}
				}

				break;
			}
			}
			return false;
		}
	};

	// Sự kiện chạm trên listScience
	private OnTouchListener lstScienceOnTocuhListener = new OnTouchListener() {

		private float downX;
		private float upX;
		private float upY;
		private float downY;

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN: {
				downX = event.getX();
				downY = event.getY();
				break;
			}

			case MotionEvent.ACTION_MOVE: {
				upY = event.getY();
				if (downY < upY && scienceFirstVisibleItem == 0
						&& pgrLoading.getVisibility() == View.GONE) {
					txtUpdate.setVisibility(View.VISIBLE);
				} else {
					txtUpdate.setVisibility(View.GONE);
				}
				break;
			}

			case MotionEvent.ACTION_UP: {
				upX = event.getX();

				if (isScienceChoose) {
					if (downX < upX && downX < touchSpace) {
						// Thực hiện trượt từ Science -> Career
						doSwipeLTR(lstScience, lstCareer, btnCareer,
								R.drawable.btn_career_down);
						isCareerChoose = true;
						LoadPages();
						return true;
					}

					if (downX > upX && downX > widthView - touchSpace) {
						// Thực hiện trượt từ Science -> News
						doSwipeRTL(lstScience, lstNews, btnNews,
								R.drawable.btn_news_down);
						isNewsChoose = true;
						LoadPages();
						return true;
					}

					// Cap nhat thong tin
					if (txtUpdate.getVisibility() == View.VISIBLE) {
						txtUpdate.setVisibility(View.GONE);
						pgrLoading.setVisibility(View.VISIBLE);
						updateDataFromInternet();
					}
				}
				break;
			}
			}
			return false;
		}
	};

	private OnItemClickListener lstItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> adapter, View v, int id,
				long position) {
			urlDetailView = null;

			if (isNewsChoose) {
				urlDetailView = dataNews.get(id).getViewUrl();
			}
			if (isCareerChoose) {
				urlDetailView = dataCareer.get(id).getViewUrl();
			}
			if (isScienceChoose) {
				urlDetailView = dataScience.get(id).getViewUrl();
			}

			prdWaiting.show();
			pgrLoading.setVisibility(View.VISIBLE);
			Thread thread = new Thread() {
				public void run() {
					try {
						htmlContent = AndroidGetData
								.getDetailHTMLContent(urlDetailView);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					Message msg = Message.obtain(uiPageDetailHandler);
					uiPageDetailHandler.sendMessage(msg);
				}
			};
			thread.start();
		}

	};

	// Sự kiện scroll list
	private OnScrollListener lstOnScrollListener = new OnScrollListener() {

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {

			if (isCareerChoose) {
				careerFirstVisibleItem = firstVisibleItem;
				careerVisibleItemCount = visibleItemCount;
			}

			if (isScienceChoose) {
				scienceFirstVisibleItem = firstVisibleItem;
				scienceVisibleItemCount = visibleItemCount;
			}

			if (isNewsChoose) {
				newsFirstVisibleItem = firstVisibleItem;
			}

			if (isCareerChoose || isScienceChoose) {

				boolean rs = (firstVisibleItem + visibleItemCount >= totalItemCount);

				if (rs) {
					btnSeeMore.setVisibility(View.VISIBLE);
				} else {
					btnSeeMore.setVisibility(View.GONE);
				}
			}
		}

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {

		}

	};

	// ==============KHỐI CÁC HÀM HỖ TRỢ=================

	// Tắt tất cả các nút bấm
	private void setOffAllButton() {
		isNewsChoose = false;
		isCareerChoose = false;
		isScienceChoose = false;
		isIntroChoose = false;

		btnNews.setBackgroundResource(R.drawable.btn_news);
		btnCareer.setBackgroundResource(R.drawable.btn_career);
		btnScience.setBackgroundResource(R.drawable.btn_science);
		btnIntro.setBackgroundResource(R.drawable.btn_intro);
	}

	// Ẩn tất cả các content
	private void setInvisibleView() {
		lstNews.setVisibility(View.GONE);
		lstCareer.setVisibility(View.GONE);
		lstScience.setVisibility(View.GONE);
		imgIntro.setVisibility(View.GONE);
	}

	// Xử lý trượt từ trái qua phải
	private void doSwipeLTR(ListView lstCurrent, ListView lstCome,
			Button btnCome, int idBtnCome) {

		// Hiệu ứng
		lstCurrent.startAnimation(aniCTR);
		setInvisibleView();

		lstCome.startAnimation(aniLTC);
		lstCome.setVisibility(View.VISIBLE);

		// Nút bấm
		setOffAllButton();
		btnCome.setBackgroundResource(idBtnCome);
	}

	// Xử lý trượt từ phải qua trái
	private void doSwipeRTL(ListView lstCurrent, ListView lstCome,
			Button btnCome, int idBtnCome) {

		// Hiệu ứng
		lstCurrent.startAnimation(aniCTL);
		setInvisibleView();

		lstCome.startAnimation(aniRTC);
		lstCome.setVisibility(View.VISIBLE);

		// Nút bấm
		setOffAllButton();
		btnCome.setBackgroundResource(idBtnCome);
	}

	// Load khi truot
	private void LoadPages() {

		pgrLoading.setVisibility(View.GONE);
		btnSeeMore.setVisibility(View.GONE);
		txtUpdate.setVisibility(View.GONE);
		if (isNewsChoose) {
			getNewsDataFromDatabase(DatabaseHelper.Table_TinMoi, dataNews,
					adapterNews);
		}

		if (isCareerChoose) {
			getNewsDataFromDatabase(DatabaseHelper.Table_ViecLam, dataCareer,
					adapterCareer);
			if (dataCareer.size() == 0) {
				GetNewCareer();
			}

			// Hien an nut xem them
			if (careerFirstVisibleItem + careerVisibleItemCount >= lstCareer
					.getCount()) {
				btnSeeMore.setVisibility(View.VISIBLE);
			}

		}

		if (isScienceChoose) {
			getNewsDataFromDatabase(DatabaseHelper.Table_KhoaHoc, dataScience,
					adapterScience);
			if (dataScience.size() == 0) {
				GetNewScience();
			}

			// hien nut xem them
			if (scienceFirstVisibleItem + scienceVisibleItemCount >= lstScience
					.getCount()) {
				btnSeeMore.setVisibility(View.VISIBLE);
			}
		}
	}

	// get data from database
	private void getNewsDataFromDatabase(String tableName,
			ArrayList<News> root, ListNewsAdapter adapter) {
		if (root.size() == 0) {
			root.addAll(database.getAllList(tableName));
			adapter.notifyDataSetChanged();
		}
	}

	// get new news data
	private void getNewNewsDataOnInternet(final String dataType,
			final Handler handler, final int pageIndex) {
		synchronized (dataType) {
			Thread thread = new Thread() {
				public void run() {
					try {

						if (dataType.equals(AndroidDataFactory.TIN_MOI)) {

							tempData = (ConvertTools
									.convertToListNews(AndroidDataFactory
											.getListNewsPreview(dataType)));
						} else {
							tempData = (ConvertTools
									.convertToListNews(AndroidDataFactory
											.getListNewsPreview(dataType,
													pageIndex)));
						}

						Message msg = Message.obtain(handler);
						handler.sendMessage(msg);
					} catch (IOException e) {
						e.printStackTrace();
					} finally {

					}
				}
			};
			thread.start();
		}
	}

	// Lay thong tin trang moi - xem them
	private void getPageNews(int pageIndex) {
		getNewNewsDataOnInternet(AndroidDataFactory.TIN_MOI, uiNewsHandler,
				pageIndex);
	}

	// Lay thong tin trang moi - xem them
	private void getPageScience(int pageIndex) {
		getNewNewsDataOnInternet(AndroidDataFactory.KHOA_HOC, uiScienceHandler,
				pageIndex);
	}

	// Lay thong tin trang moi - xem them
	private void getPageCareer(int pageIndex) {
		getNewNewsDataOnInternet(AndroidDataFactory.VIEC_LAM, uiCareerHandler,
				pageIndex);
	}

	// update data from internet
	private void updateDataFromInternet() {
		if (isCareerChoose) {
			GetNewCareer();
		} else if (isScienceChoose) {
			GetNewScience();
		} else if (isNewsChoose) {
			GetNewNews();
		}
	}

	// laays tin moi - cap nhat
	private void GetNewNews() {
		getNewNewsDataOnInternet(AndroidDataFactory.TIN_MOI, uiNewsHandler, 0);
	}

	// lay tin khoa hoc moi - cap nhat
	private void GetNewScience() {
		getNewNewsDataOnInternet(AndroidDataFactory.KHOA_HOC, uiScienceHandler,
				0);
	}

	// lay tin Viec Lam moi - cap nhat
	private void GetNewCareer() {
		getNewNewsDataOnInternet(AndroidDataFactory.VIEC_LAM, uiCareerHandler,
				0);
	}

	class UINewNewsHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			synchronized (msg) {
				int size = dataNews.size();
				Tools.insertListToList(dataNews, tempData);
				if (size < dataNews.size()) {
					adapterNews.notifyDataSetChanged();
					// database.deleteAllRecord(DatabaseHelper.Table_TinMoi);
					database.insertAllList(DatabaseHelper.Table_TinMoi,
							dataNews);
				}
				pgrLoading.setVisibility(View.GONE);
				super.handleMessage(msg);
			}
		}
	}

	class UINewScienceHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			synchronized (msg) {
				int size = dataScience.size();
				Tools.insertListToList(dataScience, tempData);
				if (size < dataScience.size()) {
					adapterScience.notifyDataSetChanged();
					// database.deleteAllRecord(DatabaseHelper.Table_KhoaHoc);
					database.insertAllList(DatabaseHelper.Table_KhoaHoc,
							dataScience);
				}
				pgrLoading.setVisibility(View.GONE);
				super.handleMessage(msg);
			}
		}
	}

	class UINewCareerHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			synchronized (msg) {
				int size = dataCareer.size();
				Tools.insertListToList(dataCareer, tempData);
				if (size < dataCareer.size()) {
					adapterCareer.notifyDataSetChanged();
					// database.deleteAllRecord(DatabaseHelper.Table_ViecLam);
					database.insertAllList(DatabaseHelper.Table_ViecLam,
							dataCareer);
				}
				pgrLoading.setVisibility(View.GONE);
				super.handleMessage(msg);
			}
		}
	}

	class UIPageDetailHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			synchronized (msg) {
				prdWaiting.dismiss();
				pgrLoading.setVisibility(View.GONE);
				Intent i = new Intent(PageMain.this, PageDetail.class);
				i.putExtra(Constant.EXTRA_URL_VIEW, htmlContent);
				startActivity(i);

				super.handleMessage(msg);
			}
		}
	}

}